package com.sbio.udiapp.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.sbio.udiapp.common.bean.Stock;

import java.util.ArrayList;
import java.util.List;

public class StockAdapter extends ArrayAdapter<Stock> implements Filterable {
    private List<Stock> originalData;
    private List<Stock> filteredData;

    public StockAdapter(Context context, List<Stock> stocks) {
        super(context, 0, stocks);
        originalData = new ArrayList<>(stocks);
        filteredData = new ArrayList<>();
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Stock stock = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        }

        TextView textView = convertView.findViewById(android.R.id.text1);
        textView.setText(stock != null ? stock.getName() : "");

        return convertView;
    }

    @NonNull
    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    String query = constraint.toString().toLowerCase();
                    filteredData.clear();
                    for (Stock stock : originalData) {
                        if (stock.getName().toLowerCase().contains(query)) {
                            filteredData.add(stock);
                        }
                    }
                    filterResults.values = filteredData;
                    filterResults.count = filteredData.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                clear();
                if (results != null && results.count > 0) {
                    addAll((List<Stock>) results.values);
                    notifyDataSetChanged();
                }
            }
        };
    }
}
